import { CommonForm } from '@/pages/OrderModule/common/components/CommonForm';
import { CommonModal } from '@/pages/OrderModule/common/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import SubTitle from '@/pages/OrderModule/common/components/SubTitle';
import Typography from '@/pages/OrderModule/common/components/Typography';
import { Alert, Col, Form, Input, Radio, Row, message } from 'antd';
import OrderStatusLabelValue from '../../components/OrderStatusLabelValue';
import PriceFormat from '../../components/PriceFormat';
import Api from '../../service';
import { useEffect, useState } from 'react';
import { countOrderSum } from '../../utils/checkOrderConfig';
import { updateOrderStatus } from '../../utils/orderStatus';
import { renderAmountDesc } from '../../utils/utils';

const amountEl = renderAmountDesc();
//作废原因
function ReasonSelect(props) {
	return (
		<div>
			<Radio.Group {...props} style={{ width: '100%', display: 'flex', flexWrap: 'wrap' }}>
				{props.reasonList.map((item) => {
					return (
						<div style={{ width: '50%', marginTop: 12 }} key={item.value}>
							<Radio value={item.key} key={item.key}>{item.value}</Radio>
						</div>
					);
				})}
			</Radio.Group>
		</div>
	);
}

/** 作废订单 */
function VoidOrderModal(props) {
	const [form] = Form.useForm();

	const { item = {}, singleIdForArray, selectKeys, orderList, handleOk, handleCancel } = props;
	const { scene = 'voidOrder' } = item;

	//当前是操作还是取消
	const [isOk, setIsOk] = useState(false);

	const [loading, setLoading] = useState(false);

	//预览数据
	const [previewData, setPreviewData] = useState({});

	//作废原因
	const [reasonList, setReasonList] = useState([]);

	const [open, setOpen] = useState(false);

	useEffect(() => {
		getPreviewData();
		getReasonList();
		setOpen(true);
	}, [])

	//作废原因
	const getReasonList = async () => {
		const {success, data} = await Api.getInvalidReason();
		if(success) {
			setReasonList(data);
		}
	}

	//获取预览数据
	const getPreviewData = async () => {
		setLoading(true);
		const params = {
			orderIds: singleIdForArray || selectKeys,
		}
		const { success, data } = await Api.voidOrder(params);
		if (success) {
			setPreviewData(data);
		}
		setLoading(false);
	}

	const onOk = () => {
		const formData = form.getFieldsValue();
		if (!formData.reason) {
			message.info('请选择作废原因');
			return;
		}
		setLoading(true);
		updateOrderStatus(scene, {
			orderIds: singleIdForArray || selectKeys,
			tradeNo: previewData.tradeNo,
			...formData
		}, (val) => {
			setLoading(false);
			if (val) {
				setIsOk(true);
				setOpen(false);
			}
		})
	}

	const onCancel = () => {
		setOpen(false);
	}

	const afterClose = () => {
		if (isOk) {
			handleOk()
		} else {
			handleCancel();
		}
	}

	//待发货的订单
	const orderCount = singleIdForArray ? null : countOrderSum(scene, selectKeys, orderList);


	//金额渲染
	const renderAmount = () => {
		const { resultHandleType, refundAmountCount = {} } = previewData;
		if (resultHandleType == 2) {
			return (
				<>
					<SubTitle
						wrapStyle={{ marginTop: 12 }}
						symbol
						as="a2"
						title="作废金额"
						extraText="（针对已支付的代发订单，作废或反审核将会对金额进行处理）"
						helpInfo={{
							content: amountEl,
						}}
					/>
					<div style={{ marginTop: 12 }}>
						退回金额：
						<PriceFormat price={refundAmountCount.totalPayAmount} />
						（含运费
						<PriceFormat price={refundAmountCount.logisticsAmount} />
						、包材费
						<PriceFormat price={refundAmountCount.packedAmount} />
						、服务费
						<PriceFormat price={refundAmountCount.serviceAmount} />）
					</div>
					<div style={{ marginTop: 12 }}>
						退货退款：
						<PriceFormat price={refundAmountCount.refundGoodsAmount} />
					</div>
				</>
			)
		}
		return null;
	}

	return (
		<CommonModal title={{title: "作废订单" }} afterClose={afterClose} open={open} width="550px" onOk={onOk} onCancel={onCancel}>
			<CommonForm
				formProps={{
					form,
					size: 'middle',
				}}
				columns={[
					{
						block: (
							<>
							{
								!singleIdForArray && (<>
									<Alert showIcon message={<Typography as="s1">您正在作废订单，“待发货”的订单一旦作废将会同步仓库，请仔细考虑操作！</Typography>} />
									<Row style={{ marginTop: 16, color: '#333' }} gutter={80}>
										<Col>
											<OrderStatusLabelValue label="待审核" value={orderCount[0]} />
										</Col>
										<Col>
											<OrderStatusLabelValue label="异常" type="error" value={orderCount[2]} />
										</Col>
										<Col>
											<OrderStatusLabelValue label="待发货" value={orderCount[1]} />
										</Col>
									</Row>
								</>)
							}
								{renderAmount()}
								<SubTitle wrapStyle={{ marginTop: 12 }} symbol as="a2" title="作废原因" extraText="（必选）" />
							</>
						),
					},
					{
						name: 'reason',
						slot: <ReasonSelect reasonList={reasonList} />,
					},
					{
						Component: Input,
						name: 'cancelMsg',
						props: {
							style: {
								marginTop: 22,
							},
							autoComplete: false,
							placeholder: '请输入作废说明',
							maxLength: 30,
							showCount: true,
						},
					},
				]}
			></CommonForm>
			<CommonLoading loading={loading} />
		</CommonModal>
	);
}

export default VoidOrderModal;
